package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryAll() {
        //从缓存中获取店铺类型
        String cacheKey = "ALL_SHOP_TYPE";
        String shopType = stringRedisTemplate.opsForValue().get(cacheKey);
        //判断是否存在
        if(shopType != null){
            //如果存在直接返回店铺类型
            return JSONUtil.toList(shopType,ShopType.class);
        }
        //如果不存在查询数据库
        List<ShopType> typeList = list(Wrappers.<ShopType>query().orderByAsc("sort"));
        if(typeList == null){
            return (List<ShopType>) Result.fail("该店铺类型不存在");
        }
        //并将从数据库中查询到的店铺类型，返回给缓存，下一次请求直接从缓存中取
        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(typeList),30, TimeUnit.MINUTES);
        //返回店铺类型
        return typeList;
    }
}
